require.config({
    baseUrl: '/js',
    paths: {
        jquery: 'jquery.min',
        i18n: 'jquery.i18n.properties-min',
        bootstrap: 'bootstrap.min',
        contabs: 'plugins/contabs/contabs',// TAB
        screenfull: 'plugins/screenfull/screenfull',// 全屏
        slimscroll: 'plugins/slimscroll/jquery.slimscroll.min',// 滚动条美化
        layer: 'plugins/layer/layer',// 弹出层
        sockjs: ['sockjs.min'],
        ace: ['ace/ace.min'],// ACE
        aceElements: 'ace/ace-elements.min',
        aceExtra: 'ace/ace-extra.min',
        myAce: ['ace/myAce'],
        template: ['template'],
        eyc: ['eyc']
    },
    map: {
        '*': {
            'css': 'require-css.min'// 事先加载css.js
        }
    },
    shim: {
        'jquery': {
            exports: '$'
        },
        'i18n': {
            deps: ['jquery']
        },
        'bootstrap': {
            deps: ['jquery']
        },
        'contabs': {
            deps: ['jquery']
        },
        'layer': {
            deps: ['jquery', 'css!plugins/layer/theme/default/layer.css']
        },
        'slimscroll': {
            deps: ['jquery']
        },
        'ace': {
            deps: ['jquery', 'bootstrap']
        },
        'aceElements': {
            deps: ['ace']
        },
        'aceExtra': {
            deps: ['ace']
        },
        'myAce': {
            deps: ['ace', 'aceElements', 'aceExtra'],
            exports: 'myAce'
        },
        'eyc': {
            deps: ['jquery', 'contabs'],
            exports: 'eyc'
        }
    }
});

require(['template', 'jquery', 'i18n', 'bootstrap', 'contabs', 'screenfull', 'slimscroll', 'sockjs', 'ace',
    'aceElements', 'aceExtra', 'myAce', 'layer', 'eyc'], function (template) {

    $(document).ready(function () {
        // 初始化ACE UI
        try {
            ace.demo.init(true);
        } catch (e) {
        }

        // 显示菜单
        loadMenuRes();

        // 初始化Tabs
        contabs.init({
            contentHeight: getIFrameHeight()
        });

        // 个人信息
        if (userId && userId.length > 0)
            $('.userIdTxt').text(", " + userId.substring(0, 1).toUpperCase() + userId.substring(1));
        else
            $('.userIdTxt').text(", " + userId);

        // 快速查询区
        $(".quickSearch button").on("click", function () {
            layer.msg("敬请期待");
        });



        $(".showMilestone").on("click", function () {
            showVersionMsg();
        });





        // WebSocket
        createWebSocket();

        // 绑定消息事件
        $('.alertInfo').click(function () {
        });

        $(".showAllNotice").on("click", function () {
            eyc.contabs.openNewPageByUrl("/eyc-web/notice/page/searchMyNotice", "我的消息");
        });


    });

    function loadMenuRes() {
    	var menuList=[
			{
				"resUuid": "a265eea0c44c4d25a6a6cd6736f6a664",
				"resId": "menu.waybill",
				"resNme": "订单管理",
				"parentResUuid": null,
				"url": null,
				"permission": "ROLE_WAYBILL_PAGE",
				"icon": "icon-waybill",
				"seq": 10,
				"isMenu": true,
				"isActive": true,
				"subResList": [
					{
						"resUuid": "34d3dbf84ea141d8818430e44e6433a7",
						"resId": "menu.wbl.searchAuditWaybill",
						"resNme": "订单列表",
						"parentResUuid": "a265eea0c44c4d25a6a6cd6736f6a664",
						"url": "/page/orderList",
						"permission": "ROLE_SRCH_AUDIT_WBL_PAGE",
						"icon": null,
						"seq": 2,
						"isMenu": true,
						"isActive": true,
						"subResList": null
					},
					{
						"resUuid": "1013aec75ee1495d98a3985218dc1210",
						"resId": "menu.wbl.insertWaybill",
						"resNme": "商户列表",
						"url": "/page/inspStationList",
						"isMenu": true,
						"isActive": true,
						"subResList": null
					}

				]
			},
			{
				"resUuid": "f2d9c60d5c07464c9f8738c4b5562dca",
				"resId": "menu.baseData",
				"resNme": "基础数据",
				"parentResUuid": null,
				"url": null,
				"permission": "ROLE_OB_WBL_PAGE",
				"icon": "icon-ob",
				"seq": 11,
				"isMenu": true,
				"isActive": true,
				"subResList": [
					{
						"resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
						"resId": "menu.wbl.VoyCtrlOb",
						"resNme": "客户管理",
						"parentResUuid": "f2d9c60d5c07464c9f8738c4b5562dca",
						"url": "/page/outerUserList",
						"permission": "ROLE_VOY_CTRL_OB_PAGE",
						"icon": null,
						"seq": 1,
						"isMenu": true,
						"isActive": true,
						"subResList": null
					},
					{
						"resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
						"resId": "menu.wbl.VoyCtrlOb",
						"resNme": "用户管理",
						"url": "/page/innerUserList",
                        "isMenu": true,
                        "isActive": true
                    },
                    {
                        "resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
                        "resId": "menu.wbl.VoyCtrlOb",
                        "resNme": "基础配置",
                        "url": "/page/dataConfig",
                        "isMenu": true,
                        "isActive": true
                    },
                    {
                        "resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
                        "resId": "menu.wbl.VoyCtrlOb",
                        "resNme": "轮播图配置",
                        "url": "/page/configCarousel",
                        "isMenu": true,
                        "isActive": true
                    },
                    {
                        "resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
                        "resId": "menu.wbl.VoyCtrlOb",
                        "resNme": "信息发布",
                        "url": "/page/publicInfo",
                        "isMenu": true,
                        "isActive": true
                    },
                    {
                        "resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
                        "resId": "menu.wbl.VoyCtrlOb",
                        "resNme": "年检价格配置",
                        "url": "/page/inspPriceConfig",
                        "isMenu": true,
                        "isActive": true
                    },
                    {
                        "resUuid": "0eedeb61df654254b2a5fbf5eea0fea8",
                        "resId": "menu.wbl.VoyCtrlOb",
                        "resNme": "消息管理",
                        "url": "/page/eycMessage",
                        "isMenu": true,
                        "isActive": true
                    }
				]
			}

		];
        showMenu(menuList, $("#side-menu"), true);
        // 绑定菜单事件
        $(".J_menuItem").on("click", function () {
            contabs.addNewTab({
                url: $(this).attr("url"),
                title: $.trim($(this).text()),
                icon: $(this).attr("icon")
            });
        });

    }

    function showMenu(menuList, parent, isTopLevel) {
        for (var menu in menuList) {
            if (!menuList[menu].isMenu)
                continue;

            // 节点
            var li = $("<li></li>");
            li.appendTo(parent);
            var a = $("<a></a>").appendTo(li);

            // 图标
            if (isTopLevel) {
                var i = $("<i></i>").appendTo(a);
                i[0].className = "menu-icon";
                if (menuList[menu].icon) {
                    i.addClass(' icon iconfont ' + menuList[menu].icon);
                }
            }
            // 菜单名
            var span = $("<span></span>").appendTo(a);
            span.append(menuList[menu].resNme)
            span[0].className = "menu-text";

            var b = $("<b></b>").appendTo(li);
            b[0].className = "arrow";

            // 判断子节点是否含有菜单
            var hasMenu = false;
            var subList = menuList[menu].subResList;
            for (var idx in subList) {
                if (subList[idx].isMenu)
                    hasMenu = true;
            }

            // 父节点
            if (hasMenu && menuList[menu].subResList && menuList[menu].subResList.length > 0) {
                // 下拉箭头
                a[0].className = "dropdown-toggle";
                var bArrow = $("<b></b>").appendTo(a);
                bArrow[0].className = "arrow icon iconfont icon-fold";
                // 子节点
                var ul = $("<ul></ul>").appendTo(li);
                ul[0].className = "submenu";
                // 递归
                showMenu(menuList[menu].subResList, ul, false);
            }
            // 子节点
            else {
                a.attr("url", menuList[menu].url);
                a.attr("icon", menuList[menu].icon);
                a.addClass('J_menuItem');
            }
        }
    }


    // IFrame高度
    function getIFrameHeight() {
        var iframeHeight = $(window).height() - $('.navbar').outerHeight() - $('.content-tabs').outerHeight();

        // 如果菜单在顶部
        if ($('.h-sidebar').outerHeight())
            iframeHeight = iframeHeight - $('.h-sidebar').outerHeight();

        return iframeHeight;
    }

    function customStyle() {
        // 刷新IFrame高度
        $(window).bind('resize', function () {
            contabs.fixContentSizes(getIFrameHeight());
        });

        // Style
        myAce.customStyle();
    }

    // Web Socket
    var websocket;
    var lockWsReconnect;
    var wsReconnectCount;
    var timeWebSocket;

    function createWebSocket() {
        try {
            var path = document.location.origin;
            path = path.substring(path.indexOf("//"));

            var isSsl = document.location.origin.toLocaleLowerCase().startsWith("https");

            if ('WebSocket' in window) {
                websocket = new WebSocket((isSsl ? "wss:" : "ws:") + path + "/eycMessage");
            } else if ('MozWebSocket' in window) {
                websocket = new MozWebSocket((isSsl ? "wss:" : "ws:") + path + "/eycMessage");
            } else {
                websocket = new SockJS((isSsl ? "https:" : "http:") + path + "/eycMessage_SockJS");
            }

            websocket.onopen = function (evnt) {
                // 心跳检测重置
                wsHeartCheck.start();
                // 重置尝试次数
                wsReconnectCount = 0;
            };

            websocket.onmessage = function (evnt) {
                wsHeartCheck.start();

                if (!evnt || !evnt.data || evnt.data === "123456789")
                    return;

                try {
                    layer.alert(evnt.data, {
                        offset: 'rb'
                    });
                } catch (e) {
                }
            };

            websocket.onerror = function (evnt) {
                reconnectWebSocket();
            };

            websocket.onclose = function (evnt) {
                reconnectWebSocket();
            };
        } catch (e) {
            reconnectWebSocket();
        }
    }

    function reconnectWebSocket() {
        if (lockWsReconnect) {
            return;
        }

        lockWsReconnect = true;

        // 没连接上30s重连一次
        timeWebSocket && clearTimeout(timeWebSocket);

        // 最多尝试10次
        if (!wsReconnectCount)
            wsReconnectCount = 0;
        wsReconnectCount++;

        if (wsReconnectCount > 10)
            return;

        timeWebSocket = setTimeout(function () {
            createWebSocket();
            lockWsReconnect = false;
        }, 30000);
    }

    // 心跳检测
    var wsHeartCheck = {
        timeout: 30000,
        timeoutObj: null,
        serverTimeoutObj: null,
        start: function () {
            var self = this;
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function () {
                // 这里发送一个心跳，后端收到后，返回一个心跳消息，
                // onmessage拿到返回的心跳就说明连接正常
                // 若没有在指定之间内获得返回，关闭后重连
                websocket.send("123456789");
                self.serverTimeoutObj = setTimeout(function () {
                    websocket.close();
                }, self.timeout);

            }, this.timeout)
        }
    };

    // 加载国际化配置
    var timeI18n;




    // 欢迎页
    function welcomeInfo() {
        if (('localStorage' in window) && window['localStorage'] !== null) {
            var curr_welcome_info = "";// 当前欢迎ID
            var welcome_info = localStorage.getItem("welcome_info");
            if (curr_welcome_info && (!welcome_info || welcome_info != curr_welcome_info)) {
                localStorage.setItem("welcome_info", curr_welcome_info);
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shadeClose: false,
                    resize: false,
                    area: ['400px', '600px'],
                    skin: 'demo-class',
                    content: '/welcome'
                });
            }
        }
    }


});

/**
 * 版本里程碑详情
 *
 * @returns
 */
function showVersionMsg() {
    eyc.contabs.openNewPageByUrl("/milestone", "里程碑");
}
